using Microsoft.AspNetCore.Mvc;
using SPI.AgentServer.Models;
using SPI.AgentServer.Services.Export;
using SPI.AgentServer.Services.Tools;
using Swashbuckle.AspNetCore.Annotations;
using System.Text.Json;

namespace SPI.AgentServer.Controllers;

/// <summary>
/// 数据导出控制器
/// 提供查询结果的 Excel、CSV 导出功能
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class ExportController : ControllerBase
{
    private readonly IExportService _exportService;
    private readonly IToolExecutor _toolExecutor;
    private readonly ILogger<ExportController> _logger;

    public ExportController(
        IExportService exportService,
        IToolExecutor toolExecutor,
        ILogger<ExportController> logger)
    {
        _exportService = exportService;
        _toolExecutor = toolExecutor;
        _logger = logger;
    }

    /// <summary>
    /// 导出工具查询结果
    /// </summary>
    /// <remarks>
    /// 执行指定工具的查询，并将结果导出为 Excel 或 CSV 文件
    /// 
    /// 示例请求：
    /// ```json
    /// {
    ///   "toolName": "get_oncampus_visitor_vehicles",
    ///   "parameters": {},
    ///   "format": "excel",
    ///   "fileName": "在校外来车辆",
    ///   "sheetName": "车辆列表"
    /// }
    /// ```
    /// </remarks>
    [HttpPost("tool")]
    [SwaggerOperation(
        Summary = "导出工具查询结果",
        Description = "执行指定工具的查询并导出为文件",
        OperationId = "ExportToolResult",
        Tags = new[] { "Export" }
    )]
    [SwaggerResponse(200, "导出成功，返回文件流", typeof(FileStreamResult))]
    [SwaggerResponse(400, "请求参数错误")]
    [SwaggerResponse(500, "服务器错误")]
    public async Task<IActionResult> ExportToolResult([FromBody] ExportRequest request)
    {
        try
        {
            _logger.LogInformation("开始导出工具 {ToolName} 的查询结果，格式：{Format}", 
                request.ToolName, request.Format);

            // 执行工具查询
            var toolInstruction = new ToolInstruction
            {
                Tool = request.ToolName,
                Parameters = request.Parameters
            };

            var toolResult = await _toolExecutor.ExecuteToolAsync(toolInstruction);

            if (!toolResult.Success)
            {
                return BadRequest(new
                {
                    message = "工具执行失败",
                    errors = toolResult.Errors
                });
            }

            // 准备导出数据
            var exportData = toolResult.Data;
            var fileName = request.FileName ?? $"{request.ToolName}_{DateTime.Now:yyyyMMdd_HHmmss}";
            var sheetName = request.SheetName ?? "数据";

            // 根据格式导出
            ExportResult exportResult;
            if (request.Format.ToLower() == "csv")
            {
                exportResult = await _exportService.ExportToCsvAsync(exportData!, fileName);
            }
            else
            {
                exportResult = await _exportService.ExportToExcelAsync(exportData!, fileName, sheetName);
            }

            _logger.LogInformation("导出成功：{FileName}，大小：{Size} 字节", 
                exportResult.FileName, exportResult.FileSize);

            // 返回文件
            return File(
                exportResult.Stream,
                exportResult.ContentType,
                exportResult.FileName
            );
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "导出失败");
            return StatusCode(500, new { message = $"导出失败：{ex.Message}" });
        }
    }

    /// <summary>
    /// 批量导出（多工作表 Excel）
    /// </summary>
    /// <remarks>
    /// 执行多个工具查询，并将结果导出到同一个 Excel 文件的不同工作表
    /// 
    /// 示例请求：
    /// ```json
    /// {
    ///   "fileName": "校园综合统计",
    ///   "queries": {
    ///     "在校外来车辆": {
    ///       "toolName": "get_oncampus_visitor_vehicles",
    ///       "parameters": {}
    ///     },
    ///     "设备统计": {
    ///       "toolName": "get_device_stats",
    ///       "parameters": {}
    ///     }
    ///   }
    /// }
    /// ```
    /// </remarks>
    [HttpPost("batch")]
    [SwaggerOperation(
        Summary = "批量导出多个查询结果",
        Description = "执行多个工具查询并导出到一个 Excel 文件的多个工作表",
        OperationId = "BatchExport",
        Tags = new[] { "Export" }
    )]
    [SwaggerResponse(200, "导出成功，返回文件流", typeof(FileStreamResult))]
    [SwaggerResponse(400, "请求参数错误")]
    [SwaggerResponse(500, "服务器错误")]
    public async Task<IActionResult> BatchExport([FromBody] BatchExportRequest request)
    {
        try
        {
            _logger.LogInformation("开始批量导出，工作表数量：{Count}", request.Queries.Count);

            var sheets = new Dictionary<string, object>();

            // 执行每个查询
            foreach (var query in request.Queries)
            {
                var toolInstruction = new ToolInstruction
                {
                    Tool = query.Value.ToolName,
                    Parameters = query.Value.Parameters
                };

                var toolResult = await _toolExecutor.ExecuteToolAsync(toolInstruction);

                if (toolResult.Success && toolResult.Data != null)
                {
                    sheets[query.Key] = toolResult.Data;
                }
                else
                {
                    _logger.LogWarning("工作表 {SheetName} 的查询失败或无数据", query.Key);
                    // 添加空数据以保留工作表
                    sheets[query.Key] = new List<object>();
                }
            }

            if (sheets.Count == 0)
            {
                return BadRequest(new { message = "所有查询都失败了" });
            }

            // 导出为多工作表 Excel
            var fileName = request.FileName ?? $"batch_export_{DateTime.Now:yyyyMMdd_HHmmss}";
            var exportResult = await _exportService.ExportToExcelMultiSheetAsync(sheets, fileName);

            _logger.LogInformation("批量导出成功：{FileName}，大小：{Size} 字节", 
                exportResult.FileName, exportResult.FileSize);

            return File(
                exportResult.Stream,
                exportResult.ContentType,
                exportResult.FileName
            );
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "批量导出失败");
            return StatusCode(500, new { message = $"批量导出失败：{ex.Message}" });
        }
    }

    /// <summary>
    /// 导出自定义数据
    /// </summary>
    /// <remarks>
    /// 直接提供数据进行导出，不需要执行工具查询
    /// 
    /// 示例请求：
    /// ```json
    /// {
    ///   "data": [
    ///     {"姓名": "张三", "年龄": 25},
    ///     {"姓名": "李四", "年龄": 30}
    ///   ],
    ///   "format": "excel",
    ///   "fileName": "自定义数据"
    /// }
    /// ```
    /// </remarks>
    [HttpPost("custom")]
    [SwaggerOperation(
        Summary = "导出自定义数据",
        Description = "直接提供数据进行导出",
        OperationId = "ExportCustomData",
        Tags = new[] { "Export" }
    )]
    [SwaggerResponse(200, "导出成功，返回文件流", typeof(FileStreamResult))]
    [SwaggerResponse(400, "请求参数错误")]
    [SwaggerResponse(500, "服务器错误")]
    public async Task<IActionResult> ExportCustomData([FromBody] JsonElement request)
    {
        try
        {
            // 解析请求
            var data = request.GetProperty("data");
            var format = request.TryGetProperty("format", out var formatProp) 
                ? formatProp.GetString() ?? "excel" 
                : "excel";
            var fileName = request.TryGetProperty("fileName", out var fileNameProp) 
                ? fileNameProp.GetString() ?? $"export_{DateTime.Now:yyyyMMdd_HHmmss}" 
                : $"export_{DateTime.Now:yyyyMMdd_HHmmss}";
            var sheetName = request.TryGetProperty("sheetName", out var sheetNameProp) 
                ? sheetNameProp.GetString() ?? "数据" 
                : "数据";

            _logger.LogInformation("开始导出自定义数据，格式：{Format}", format);

            // 导出
            ExportResult exportResult;
            if (format.ToLower() == "csv")
            {
                exportResult = await _exportService.ExportToCsvAsync(data, fileName);
            }
            else
            {
                exportResult = await _exportService.ExportToExcelAsync(data, fileName, sheetName);
            }

            _logger.LogInformation("导出成功：{FileName}，大小：{Size} 字节", 
                exportResult.FileName, exportResult.FileSize);

            return File(
                exportResult.Stream,
                exportResult.ContentType,
                exportResult.FileName
            );
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "导出自定义数据失败");
            return StatusCode(500, new { message = $"导出失败：{ex.Message}" });
        }
    }

    /// <summary>
    /// 获取可导出的工具列表
    /// </summary>
    [HttpGet("available-tools")]
    [SwaggerOperation(
        Summary = "获取可导出的工具列表",
        Description = "返回所有可以用于导出的工具名称",
        OperationId = "GetAvailableTools",
        Tags = new[] { "Export" }
    )]
    public IActionResult GetAvailableTools()
    {
        var tools = _toolExecutor.GetAvailableToolNames();
        return Ok(new
        {
            tools = tools,
            count = tools.Count
        });
    }
}




